package model

import (
	"github.com/jinzhu/gorm"
)

type Credential struct {
	Name string `json:"name" gorm:"primary_key;not null"`
	// password or privateKey
	Type string `json:"type"`
	// Credential content
	CredentialData string `json:"credential_data"`
	Username       string `json:"username"`
	BaseModel
}

func (cred *Credential) GetCredentials() ([]*Credential, error) {
	var creds []*Credential

	err := db.Find(&creds).Error

	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return creds, nil
}

func (cred *Credential) GetCredentialDetails(name string) (*Credential, error) {
	var creds Credential

	err := db.Where("name = ?", name).First(&creds).Error

	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &creds, nil
}

func (cred *Credential) CheckNameIsExist(name string) bool {

	var count int
	db.Find(&Credential{
		Name: name,
	}).Count(&count)

	if count >0 {
		return true
	}

	return false
}

func (cred *Credential) AddCredential() error {

	if err := db.Create(&cred).Error; err != nil {
		return err
	}

	return nil
}

func (cred *Credential) DeleteCredential(name string) error {
	if err := db.Delete(Credential{Name: name}).Error; err != nil {
		return err
	}
	return nil
}

func (cred *Credential) EditCredential(name string, data interface{}) error {
	if err := db.Model(&Credential{}).Where("name = ?", name).Update(data).Error; err != nil {
		return err
	}

	return nil
}
